/*
 * MIT License
 *
 * Copyright (C) 2023 Huawei Device Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import { BleError } from './BleError';

export class BleErrorToJsObjectConverter {
  public toJSCallback(error: BleError): any[] {
    const result: any[] = [];
    result.push(this.toJs(error));
    result.push(null);
    return result;
  }

  public toJs(error: BleError): string {
    const obj: any = {};

    obj["errorCode"] = error.errorCode;

    obj["attErrorCode"] =
      error.harmonyCode != null && error.harmonyCode >= 0 && error.harmonyCode < 0x80 ? error.harmonyCode : null;

    obj["iosErrorCode"] = null;

    obj["harmonyErrorCode"] = error.harmonyCode != null && error.harmonyCode >= 0x80 ? error.harmonyCode : null;

    this.appendString(obj, "reason", error.reason);
    this.appendString(obj, "deviceID", error.deviceID);
    this.appendString(obj, "serviceUUID", error.serviceUUID);
    this.appendString(obj, "characteristicUUID", error.characteristicUUID);
    this.appendString(obj, "descriptorUUID", error.descriptorUUID);
    this.appendString(obj, "internalMessage", error.internalMessage);
    return JSON.stringify(obj);
  }

  private appendString(obj: any, key: string, value: string | undefined): void {
    if (value !== undefined) {
      obj[key] = value === null ? null : value;
    } else {
      obj[key] = null;
    }
  }
}